// pages/socks/socks.js
const app = getApp()
import { baseUrl, get_open_id, user_login } from "../../utils/api.js";

var utils = require('../../utils/util.js');
const {
  getTimeSeconds
} = utils
const recorderManager = wx.getRecorderManager();
const audioCtx = wx.createInnerAudioContext('myAudio')
const innerAudioContext = wx.createInnerAudioContext()
var list_show = 1;
var img_jump = false;
Page({
  /**
   * 页面的初始数据
   */
  data: {
    haveTap: 1, // 1: 可以点击 0：不可点击
    TaskShow: 0,
    newslist: [],
    newsinfo: [],
    userInfo: {},
    scrollTop: 0,
    increase: false, //图片添加区域隐藏
    aniStyle: true, //动画效果
    message: "",
    previewImgList: [],
    mic_audio: false,
    audio_mic: false,
    isaudio: true,
    audio_text: "按住 说话",
    setInter: '',
    toView: '',
    scrollHeight: '100vh',
    on_line_uid: '',
    jsid: '',
    fsid: '',
    mid: 0,
    socksuid:0
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    img_jump = false;
    if (options.jsid) {
      that.setData({
        jsid: options.jsid,
        fsid: options.fsid,
      })
    }
    if (options.mid != undefined && options.mid > 0) {
      console.log(options.mid);
      app.globalData.SwitchTabParams.v_id = options.mid;

    }
    console.log(options.socksuid);
    if (options.socksuid != undefined && options.socksuid > 0){
      that.setData({
        socksuid: options.socksuid,
      })
    }

  },



  wssInit: function () {
    var that = this;

    this.connectWss();
    wx.onSocketClose(function () {
      console.log("居然关闭了");
      that.wssconnect();
    })
    // 链接失败显示
    wx.onSocketError(function (res) {
      console.log('WebSocket连接打开失败，请检查！', res);
      that.setData({
        isOpen: false,
        statusMsg: '已断开'
      });
      that.wssconnect();

    });
    // 监听连接成功
    wx.onSocketOpen(function (res) {
      console.log('WebSocket连接已打开！')

      that.setData({
        isOpen: true,
        statusMsg: '已连接'
      });
      if (app.globalData.userInfo!=undefined){
        var param = { message: '', uid: app.globalData.userInfo.id, tuid: 0, p_id: 0, type: 1, is_read: 2, length: '', timestamp: new Date().getTime()};
        param.sign = app.getSign(param)
        wx.sendSocketMessage({
          data: JSON.stringify(param),
          success: res => {

          }
        });
      }
      
      // that.send(0)
      wx.onSocketMessage(function (res) {
        var re_data1 = res.data;
        var re_data = JSON.parse(re_data1); //可用此方法来转换
        console.log('服务西澳西')
        console.log(re_data)
        // console.log(re_data.status)
        // console.log(re_data.message)
        if (re_data.status == 1) {
          if (Number(re_data.on_line_uid) != Number(app.globalData.userInfo.id)) {

            // 发送模板消息-未读回信提醒

           
            // app.sendTemplateMessage(app.globalData.SwitchTabParams.v_id, 3, '/pages/socks/socks?jsid=' + app.globalData.SwitchTabParams.v_id + '&fsid=' + app.globalData.userInfo.id, '', '', '', '')


          }

          // if (Number(re_data.on_line_uid) != Number(app.globalData.userInfo.id)) {
          //   //         // 发送模板消息-未读回信提醒
          //   app.sendTemplateMessage(app.globalData.SwitchTabParams.v_id, 3, '/pages/contactList/contactList?mpid=' + app.globalData.SwitchTabParams.v_id + '&zjid=' + app.globalData.userInfo.id, '', '', '', '')
          // }
          var message_list = re_data.message;
          var list = [];
          var nlist = [];
          list = that.data.newslist;
          nlist = message_list;

          var room_id = '';
          var room_id2 = '';
          room_id = app.globalData.userInfo.id + '/' + app.globalData.SwitchTabParams.v_id;
          room_id2 = app.globalData.SwitchTabParams.v_id + '/' + app.globalData.userInfo.id;
          console.log('--------');
          console.log(list[list.length - 1].flag);
          console.log(nlist.flag);
          console.log('--------');
        

          if ((nlist.room_id == room_id || nlist.room_id == room_id2) && list[list.length - 1].flag != nlist.flag) {
            if (nlist != '') {
              nlist.showTime = false;

              if (nlist.type == 3) {
                nlist.isaudio = true;
                nlist.noPlay = true;
                if (!!nlist.length) {

                  if (nlist.length > 3) {
                    nlist.changeWidth = 'width:' + Number((nlist.length - 3) * 2 + 60) + 'px';
                  } else {
                    nlist.changeWidth = 'width:60px';
                  }
                } else {
                  nlist.length = '';
                  nlist.changeWidth = 'width:60px';
                }
              }

              var lst = list.length - 1;
              var d1 = list[lst].create_time;
              d1 = d1.substring(0, 19);
              d1 = d1.replace(/-/g, '/');
              var timestamp1 = new Date(d1).getTime();

              var d2 = nlist.create_time;
              d2 = d2.substring(0, 19);
              d2 = d2.replace(/-/g, '/');
              var timestamp2 = new Date(d2).getTime();
              console.log(timestamp1);
              console.log(timestamp2);
              console.log((Number(timestamp2) - Number(timestamp1)));
              if ((Number(timestamp2) - Number(timestamp1)) < 3600000) {
                nlist.showTime = false;
              } else {
                nlist.showTime = true;
              }

              //  console.log(12);




              list.push(nlist);
              console.log(">>>>>>>>>>>>>>>>>>");
              console.log(nlist);
              console.log(list);
            
              that.setData({
                newslist: list
              })

              console.log(">>>>>>>>>>>>>>>数据接受结束");

              that.setData({
                toView: 'msg-' + (that.data.newslist.length - 1)
              })
            } else {
              that.setData({
                newslist: list
              })
            }
          }


        } else if (re_data.status == 0) {
          app.showTipMsg(re_data.msg);
        }
      });
      // wx.sendSocketMessage({

      // });
    })
  },
  // 向服务器发送消息
  send: function (state) {
    var that = this;
    // console.log('尝试向服务器发送消息：'+app.globalData.SwitchTabParams.v_id);
    // that.connectWss()
    that.setData({
      increase: false
    })
    if (that.data.message.trim() == '' && state != 0) {
      wx.showToast({
        title: '内容不能为空！',
        icon: 'none',
        duration: 2000
      })
      return;
    }else{
      var list = [];
      var nlist = {};
      list = that.data.newslist;
      var room_idx = (new Date()).getTime();
      if (parseInt(app.globalData.SwitchTabParams.v_id) > parseInt(app.globalData.userInfo.id)) {
        room_idx = app.globalData.userInfo.id + '/' + app.globalData.SwitchTabParams.v_id + room_idx;

      } else {
        room_idx = app.globalData.SwitchTabParams.v_id + '/' + app.globalData.userInfo.id + room_idx;

      }


      nlist.showTime = false;
      nlist.uid = app.globalData.userInfo.id;
      nlist.a_uid = app.globalData.SwitchTabParams.v_id;
      nlist.message = that.data.message;
      nlist.type = 1;
      nlist.flag = room_idx;
      var lst = list.length - 1;
      var d1 = list[lst].create_time;
      d1 = d1.substring(0, 19);
      d1 = d1.replace(/-/g, '/');
      var timestamp1 = new Date(d1).getTime();

      var d2 = nlist.create_time = that.getNowFormatDate();
      console.log(d2);
      d2 = d2.substring(0, 19);
      d2 = d2.replace(/-/g, '/');
      var timestamp2 = new Date(d2).getTime();
      console.log(timestamp1);
      console.log(timestamp2);
      console.log((Number(timestamp2) - Number(timestamp1)));
      if ((Number(timestamp2) - Number(timestamp1)) < 3600000) {
        nlist.showTime = false;
      } else {
        nlist.showTime = true;
      }
      list.push(nlist);
      that.setData({
        newslist: list
      })


      that.setData({
        toView: 'msg-' + (that.data.newslist.length - 1)
      })
    }
    var params = { message: that.data.message, uid: app.globalData.userInfo.id, tuid: app.globalData.SwitchTabParams.v_id, p_id: that.data.newslist[0].id, type: 1, is_read: 2, length: '', flag: room_idx, timestamp: new Date().getTime() }
    params.sign = app.getSign(params)
    wx.sendSocketMessage({
      data: JSON.stringify(params),
      success: res => {
        that.setData({
          message: ''
        })

      },
      fail: res => {
        wx.showModal({
          title: '提示',
          content: '服务忙，请重新发送',
          showCancel: false,
          success: function () {
            that.wssconnect();
          }
        })

      },
    });
  },
  getNowFormatDate: function () {
    var date = new Date();
    var seperator1 = "/";
    var seperator2 = ":";
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    if(month >= 1 && month <= 9) {
      month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
      strDate = "0" + strDate;
    }
    var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
      + " " + date.getHours() + seperator2 + date.getMinutes();
    return currentdate;
  },
  connectWss: function () {
    this.setData({
      statusMsg: '连接中。。。'
    });

    this.wssconnect();
  },

  wssconnect: function () {
    //Socket连接
    var sk = wx.connectSocket({
      url: 'wss://wss.51jlkj.com/server/index/index'
    })
    this.setData({ sk: sk });
  },

  // 检测是否需要登录
  checkUserInfo: function () {
    const that = this
    that.wssInit();
    let openid = wx.getStorageSync('openid')
    if (openid) {
      app.globalData.openid = openid
      that.setData({
        openid,
      })
      let url = '/user_api/getInfoByOpenID';
      app.HttpPostSend(
        url, {
          openid: openid,
        },
        function (result_data) {
          if (result_data.msg != "success") {
            app.showTipMsg(result_data.msg);
          } else {
            if (!!result_data.data) {//如果后台有数据
              app.globalData.userInfo = {
                ...result_data.data
              }
              wx.setStorage({
                key: 'userInfo',
                data: JSON.stringify({
                  ...result_data.data
                })
              })
              that.setData({
                userInfo: result_data.data
              })

              if (!!that.data.jsid) {
                app.globalData.userInfo.id = that.data.jsid
                app.globalData.SwitchTabParams.v_id = that.data.fsid
              }

              that.getLists();
              that.changeStatus();
             
              // 雷达添加查看记录 -聊天窗口
              app.radarAdd(app.globalData.SwitchTabParams.v_id, 6, '', '', app.globalData.userInfo.logo)

              let url2 = '/user_api/onLine';
              let params2 = {
                uid: app.globalData.userInfo.id,
                on_line_uid: app.globalData.SwitchTabParams.v_id
              }
              app.HttpPostSend(url2, params2, function (res) {

              });

            } else {//如果后台无数据
              wx.login({
                success(res) {
                  let params = {
                    code: res.code
                  }
                  app.HttpGetSend(get_open_id, params, function (result) {
                    if (result.msg != "success") {
                      app.showTipMsg(result.msg);
                    } else {
                      app.globalData.openid = result.data.openid.openid;
                      app.globalData.userInfo = result.data.userinfo;
                      wx.setStorage({
                        key: 'openid',
                        data: result.data.openid.openid
                      })
                      that.setData({
                        openid: result.data.openid.openid
                      })
                      that.setData({
                        TaskShow: 1,
                        openid: result.data.openid.openid
                      })
                    }
                  })
                }
              })
            }
          }
        })
    } else {
      wx.login({
        success(res) {
          let params = {
            code: res.code
          }
          app.HttpGetSend(get_open_id, params, function (result) {
            if (result.msg != "success") {
              app.showTipMsg(result.msg);
            } else {
              app.globalData.openid = result.data.openid.openid;
              app.globalData.userInfo = result.data.userinfo;
              wx.setStorage({
                key: 'openid',
                data: result.data.openid.openid
              })
              that.setData({
                openid: result.data.openid.openid
              })
              that.setData({
                TaskShow: 1,
                openid: result.data.openid.openid
              })
            }
          }, 1)
        }
      })
    }

    let systemInfo = wx.getSystemInfoSync()
    app.globalData.systemInfo = systemInfo
    this.setData({
      systemInfo
    })

  },

  // 获取用户信息
  bindGetUserInfo: function (e) {
    const that = this
    let userInfo = e.detail.userInfo
    try {
      app.HttpPostSend(
        user_login, {
          openid: that.data.openid,
          username: userInfo.nickName,
          logo: userInfo.avatarUrl,
          sex: userInfo.gender
        },
        function (result_data) {
          if (result_data.msg != "success") {
            app.showTipMsg(result_data.msg);
          } else {
            app.globalData.authSettingUser = 1;
            let userInfo = {
              ...result_data.data
            }
            app.globalData.userInfo = userInfo
            if (!!that.data.jsid) {
              app.globalData.userInfo.id = that.data.jsid
              app.globalData.SwitchTabParams.v_id = that.data.fsid
            }
            wx.setStorage({
              key: 'userInfo',
              data: JSON.stringify(userInfo)
            })
            that.setData({
              TaskShow: 0,
              userInfo: userInfo
            })

            that.getLists();
            that.changeStatus();

            // 雷达添加查看记录 -聊天窗口
            app.radarAdd(app.globalData.SwitchTabParams.v_id, 6, '', '', app.globalData.userInfo.logo)

            let url2 = '/user_api/onLine';
            let params2 = {
              uid: app.globalData.userInfo.id,
              on_line_uid: app.globalData.SwitchTabParams.v_id
            }
            app.HttpPostSend(url2, params2, function (res) {

            });

          }
        })
    } catch (error) {

    }
  },

  //获取聊天列表数据
  getLists: function () {
    wx.showLoading({
      title: '获取数据中',
    })
    const that = this
    var timestamp = Date.parse(new Date());
    timestamp = timestamp / 1000;

    let url = '/chat_api/user_index';
    let params = {
      uid: app.globalData.userInfo.id,
      c_uid: app.globalData.SwitchTabParams.v_id
    }
    app.HttpPostSend(url, params, function (res) {
      wx.hideLoading();
      if (res.msg != "success") {
        app.showTipMsg(res.msg);
      } else {
        var list = [];
        var info = [];
        if (!!res.data) {
          list = res.data.lists;
          info = res.data.info;

          for (var i = 0; i < list.length; i++) {
            list[i].showTime = false;
            if ((Number(timestamp) - Number(list[i].create_time)) > 1800) {
              list[i].showTime = true;
            } else {
              // list[i].showTime = false;
            }

            var ii = parseInt(i) - 1;
            if (i < list.length - 1 && i > 0) {
              if ((Number(list[i].create_time) - Number(list[ii].create_time)) < 1800) {
                list[i].showTime = false;
              } else {
                list[i].showTime = true;
              }
            }
            if (i == list.length - 1 && i > 0) {
              var iii = parseInt(i) - 1;
              if ((Number(list[i].create_time) - Number(list[iii].create_time)) < 1800) {
                list[i].showTime = false;
              } else {
                list[i].showTime = true;
              }
            }
          }

          for (var i = 0; i < list.length; i++) {
            if (list[i].type == "3") {
              list[i].isaudio = true;
              list[i].noPlay = true;
              if (!!list[i].length) {

                if (list[i].length > 3) {
                  list[i].changeWidth = 'width:' + Number((list[i].length - 3) * 2 + 60) + 'px';
                } else {
                  list[i].changeWidth = 'width:60px';
                }
              } else {
                list[i].length = '';
                list[i].changeWidth = 'width:60px';
              }

            }
            list[i].create_time = that.timestampToTime(list[i].create_time * 1000);
          }
          that.setData({
            newslist: list,
            newsinfo: info,
          })
          that.setData({
            toView: 'msg-' + (that.data.newslist.length - 1)
          })
        } else {

          let url2 = '/chat_api/addInfo';
          let params2 = {
            uid: app.globalData.SwitchTabParams.v_id,
            a_uid: app.globalData.userInfo.id,
            message: '您好，欢迎进入我的店铺，有什么可以帮到您的吗？您可以在这里跟我实时沟通。',
            p_id: 0,
            type: 1,
            is_read: 2
          }
          app.HttpPostSend(url2, params2, function (res) {

            let url = '/chat_api/user_index';
            let params = {
              uid: app.globalData.userInfo.id,
              c_uid: app.globalData.SwitchTabParams.v_id
            }
            app.HttpPostSend(url, params, function (res) {
              that.setData({
                message: ''
              })
              if (res.msg != "success") {
                app.showTipMsg(res.msg);
              } else {
                var list = [];
                var info = [];
                list = res.data.lists;
                info = res.data.info;
                for (var i = 0; i < list.length; i++) {
                  if ((Number(timestamp) - Number(list[i].create_time)) > 60) {
                    list[i].showTime = true;
                  } else {
                    list[i].showTime = false;
                  }
                  var ii = parseInt(i) + 1;
                  if (ii <= list.length - 1) {
                    if ((Number(list[ii].create_time) - Number(list[i].create_time)) < 60) {
                      list[i].showTime = false;
                    } else {
                      // list[i].showTime = true;
                    }
                  }
                }

                for (var i = 0; i < list.length; i++) {
                  if (list[i].type == "3") {
                    list[i].isaudio = true;
                    list[i].noPlay = true;
                    if (!!list[i].length) {

                      if (list[i].length > 3) {
                        list[i].changeWidth = 'width:' + Number((list[i].length - 3) * 2 + 60) + 'px';
                      } else {
                        list[i].changeWidth = 'width:60px';
                      }
                    } else {
                      list[i].length = '';
                      list[i].changeWidth = 'width:60px';
                    }

                  }
                  list[i].create_time = that.timestampToTime(list[i].create_time * 1000);
                }
                that.setData({
                  newslist: list,
                  newsinfo: info,
                })
              }
            });

          });
        }
      }
    });
  },

  //更改通知状态
  changeStatus: function () {
    const that = this;
    var url2 = '/weixin_api/updateTemplateResult';
    var params2 = {
      operatorId: app.globalData.userInfo.id
    };
    app.HttpGetSend(url2, params2, function (res) {
      if (res.msg != "success") {
        app.showTipMsg(res.msg);
      }
    });
  },

  img_jump:function(e){
    var usertype = e.currentTarget.dataset.usertype;
    var cusertype = e.currentTarget.dataset.cusertype;
    var url = '';
    if (cusertype == 2){
      app.globalData.SwitchTabParams.v_id = e.currentTarget.dataset.uid
      console.log('???' + app.globalData.SwitchTabParams.v_id);
      img_jump = true
      wx.switchTab({
        url: '/pages/carteShow/carteShow'
      })
    }
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    const that = this;
    img_jump = false;
    if (list_show>0){
      that.checkUserInfo();
    }
    
    
  },
  // 页面卸载
  onUnload() {
    console.log(11);
    var that = this;


    wx.closeSocket()
    // that.data.sk.close();

    wx.onSocketClose(function () {
      console.log('Socket关闭');
      
    });
    clearInterval(that.data.setInter);

    let url2 = '/user_api/onLine';
    let params2 = {
      uid: app.globalData.userInfo.id,
      on_line_uid: 0
    }
    app.HttpPostSend(url2, params2, function (res) {

    });
    var userinfo = app.globalData.userInfo
    if (that.data.socksuid>0){

      app.globalData.SwitchTabParams.v_id = that.data.socksuid

    }else{
      if (userinfo.type != undefined && userinfo.type == 1 && userinfo.is_shop != undefined && userinfo.is_shop == 0) {

        if (!img_jump) {
          app.globalData.SwitchTabParams.v_id = 191
        }
        
        
      } else if (userinfo.type != undefined && userinfo.type == 2 && userinfo.is_shop != undefined && userinfo.is_shop == 1) {
      
        if (!img_jump){
          app.globalData.SwitchTabParams.v_id = app.globalData.userInfo.id
        }
        
      }
    }
    
  },

  // 打开个人统计信息页
  showPerson: function (e) {
    var userinfo = app.globalData.userInfo
    if (userinfo.type != undefined && userinfo.type == 1 && userinfo.is_shop != undefined && userinfo.is_shop == 0) {
      app.globalData.SwitchTabParams.v_id = 191
    } else if (userinfo.type != undefined && userinfo.type == 2 && userinfo.is_shop != undefined && userinfo.is_shop == 1) {
      app.globalData.SwitchTabParams.v_id = app.globalData.userInfo.id
    }
    wx.switchTab({
      url: '/pages/person/person',
    })
  },
  copyToCli: function (e) {
    wx.setClipboardData({
      data: e.currentTarget.dataset.message,
      success(res) {
        app.showTipMsg('复制成功')
      }
    })
  },
  timestampToTime: function (timestamp) {
    var date = new Date(timestamp);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
    var Y = date.getFullYear() + '/';
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '/';
    var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate() + "";
    var h = date.getHours() + ':';
    var m = date.getMinutes();
    if (String(m).length == 1) {
      m = "0" + m;
    }
    var s = date.getSeconds();
    return Y + M + D + " " + h + m;
    // return Y + M + D + " " + h + m + ':' + s;
  },//转化后格式xxxx-xx-xx,

  //获取对象是否在线
  getOnLine: function () {
    var that = this
    let url3 = '/user_api/getUserInfos';
    let params3 = {
      uid: app.globalData.SwitchTabParams.v_id
    }
    app.HttpPostSend(url3, params3, function (res) {
      if (res.msg != "success") {
        app.showTipMsg(res.msg);
      } else {
        that.setData({
          on_line_uid: res.data.on_line_uid
        })
      }
    });
  },

  //事件处理函数
  // send: function() {
  //   var that = this
  //   if (that.data.message == "") {
  //     wx.showToast({
  //       title: '消息不能为空哦~',
  //       icon: "none",
  //       duration: 2000
  //     })
  //   } else {
  //     setTimeout(function() {
  //       that.setData({
  //         increase: false
  //       })
  //     }, 500)
  //     that.getOnLine();

  //     let url = '/chat_api/addInfo';
  //     let params = {
  //       uid: app.globalData.userInfo.id,
  //       a_uid: app.globalData.SwitchTabParams.v_id,
  //       message: that.data.message,
  //       p_id: that.data.newslist[0].id,
  //       type: 1,
  //       is_read: 2
  //     }
  //     that.setData({
  //       message: ''
  //     })
  //     app.HttpPostSend(url, params, function (res) {
  //       if (Number(that.data.on_line_uid) != Number(app.globalData.userInfo.id)) {
  //         // 发送模板消息-未读回信提醒
  //         app.sendTemplateMessage(app.globalData.SwitchTabParams.v_id, 3, '/pages/contactList/contactList?mpid=' + app.globalData.SwitchTabParams.v_id + '&zjid=' + app.globalData.userInfo.id, '', '', '', '')
  //       }
  //     });
  //   }
  // },
  //监听input值的改变
  bindChange(res) {
    this.setData({
      message: res.detail.value
    })
  },
  cleanInput() {
    //button会自动清空，所以不能再次清空而是应该给他设置目前的input值
    this.setData({
      message: this.data.message
    })
  },
  increase() {
    var increase = this.data.increase
    this.setData({
      increase: !increase,
      aniStyle: true
    })
  },
  //点击空白隐藏message下选框
  outbtn() {
    this.setData({
      increase: false,
      aniStyle: true
    })
  },
  //发送图片
  chooseImage() {
    var that = this
    list_show = 0;
    that.wssInit();
    that.getOnLine();
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths
        wx.uploadFile({
          url: baseUrl + '/chat_api/uploadChat', //服务器地址
          filePath: tempFilePaths[0],
          name: 'file',
          headers: {
            'Content-Type': 'form-data'
          },
          success: function (resp) {
            
            let json_res = JSON.parse(resp.data)
            if (json_res.data) {
              that.setData({
                increase: false
              })
              var room_idx = (new Date()).getTime();
              if (parseInt(app.globalData.SwitchTabParams.v_id) > parseInt(app.globalData.userInfo.id)) {
                room_idx = app.globalData.userInfo.id + '/' + app.globalData.SwitchTabParams.v_id + room_idx;

              } else {
                room_idx = app.globalData.SwitchTabParams.v_id + '/' + app.globalData.userInfo.id + room_idx;

              }
              var send_param = { message: json_res.data, uid: app.globalData.userInfo.id, tuid: app.globalData.SwitchTabParams.v_id, p_id: that.data.newslist[0].id, type: 2, is_read: 2, length: '', flag: room_idx, timestamp: new Date().getTime()};
              send_param.sign = app.getSign(send_param)
              wx.sendSocketMessage({
                data: JSON.stringify(send_param),
                success: res => {
                  that.setData({
                    message: ''
                  })

                }
              });
              var list = [];
              var nlist = {};
              list = that.data.newslist;


              nlist.showTime = false;
              nlist.uid = app.globalData.userInfo.id;
              nlist.a_uid = app.globalData.SwitchTabParams.v_id;
              nlist.message = json_res.data;
              nlist.type = 2;
              nlist.flag = room_idx;
              var lst = list.length - 1;
              var d1 = list[lst].create_time;
              d1 = d1.substring(0, 19);
              d1 = d1.replace(/-/g, '/');
              var timestamp1 = new Date(d1).getTime();

              var d2 = nlist.create_time = that.getNowFormatDate();
              d2 = d2.substring(0, 19);
              d2 = d2.replace(/-/g, '/');
              var timestamp2 = new Date(d2).getTime();
              console.log(timestamp1);
              console.log(timestamp2);
              console.log((Number(timestamp2) - Number(timestamp1)));
              if ((Number(timestamp2) - Number(timestamp1)) < 3600000) {
                nlist.showTime = false;
              } else {
                nlist.showTime = true;
              }
              list.push(nlist);
              that.setData({
                newslist: list
              })
              list_show = 1;
              that.setData({
                toView: 'msg-' + (that.data.newslist.length - 1)
              })

            }
          }
        })
      }
    })
  },
  //图片预览
  previewImg(e) {
    var that = this
    //必须给对应的wxml的image标签设置data-set=“图片路径”，否则接收不到
    var res = e.target.dataset.src
    var list = this.data.previewImgList //页面的图片集合数组
    //判断res在数组中是否存在，不存在则push到数组中, -1表示res不存在
    if (list.indexOf(res) == -1) {
      this.data.previewImgList.push(res)
    }
    wx.previewImage({
      current: res, // 当前显示图片的http链接
      urls: that.data.previewImgList // 需要预览的图片http链接列表
    })
  },

  //切换语音发送
  changeMic: function () {
    this.setData({
      mic_audio: !this.data.mic_audio
    })
  },

  longTap: function () {
    console.log('longTap....')
    var that = this;
    const options = {
      duration: 60000,//指定录音的时长，单位 ms
      sampleRate: 16000,//采样率
      numberOfChannels: 1,//录音通道数
      encodeBitRate: 96000,//编码码率
      format: 'mp3',//音频格式，有效值 aac/mp3
      frameSize: 50,//指定帧大小，单位 KB
    }
    recorderManager.start(options)
    recorderManager.onStart(res => {
      console.log('recorder start')
    })
    that.setData({
      audio_mic: true,
      audio_text: "松开 结束"
    })
  },

  touchcancel: function () {
    var that = this;
    this.setData({
      audio_mic: false,
      audio_text: "按住 说话"
    })
    recorderManager.stop()
    recorderManager.onStop(res => {
      console.log('松开按钮结束:', res)
    })
  },

  //长按说话发送
  recordStart: function () {
  },

  //松开按钮结束
  recordEnd: function () {
    var that = this;
    this.setData({
      audio_mic: false,
      audio_text: "按住 说话"
    })
    recorderManager.stop()
    recorderManager.onStop(res => {
      console.log('松开按钮结束:', res)
      if (getTimeSeconds(res.duration) > 0) {
        //松开上传资源到阿里云oss
        wx.uploadFile({
          url: baseUrl + '/chat_api/uploadChat', //服务器地址
          filePath: res.tempFilePath, //音频地址
          name: 'file',
          headers: {
            'Content-Type': 'form-data'
          },
          success: function (resp) {
            let json_res = JSON.parse(resp.data);
            console.log(json_res, "上传成功时候返回得地址");
            that.submitAudio(json_res.data, getTimeSeconds(res.duration));
            that.setData({
              audio_mic: false
            })
          },
        });
        //上传结束
      }

    })
  },

  //发送语音信息
  submitAudio: function (audioUrl, len) {
    var that = this;

    var room_idx = (new Date()).getTime();
    if (parseInt(app.globalData.SwitchTabParams.v_id) > parseInt(app.globalData.userInfo.id)) {
      room_idx = app.globalData.userInfo.id + '/' + app.globalData.SwitchTabParams.v_id + room_idx;

    } else {
      room_idx = app.globalData.SwitchTabParams.v_id + '/' + app.globalData.userInfo.id + room_idx;

    }
    var send_param = { message: audioUrl, uid: app.globalData.userInfo.id, tuid: app.globalData.SwitchTabParams.v_id, p_id: that.data.newslist[0].id, type: 3, is_read: 2, length: len, flag: room_idx, timestamp: new Date().getTime()};
    send_param.sign = app.getSign(send_param)
    wx.sendSocketMessage({
      data: JSON.stringify(send_param),
      success: res => {
        that.setData({
          message: ''
        })

      }
    });
    var list = [];
    var nlist = {};
    list = that.data.newslist;

    nlist.showTime = false;
    nlist.uid = app.globalData.userInfo.id;
    nlist.a_uid = app.globalData.SwitchTabParams.v_id;
    nlist.message = audioUrl;
    nlist.type = 3;
    nlist.isaudio = true;
    nlist.noPlay = true;
    nlist.length = len;
    nlist.flag = room_idx;
    if (len) {

      if (len > 3) {
        nlist.changeWidth = 'width:' + Number((len - 3) * 2 + 60) + 'px';
      } else {
        nlist.changeWidth = 'width:60px';
      }
    } else {
      nlist.length = '';
      nlist.changeWidth = 'width:60px';
    }
    var lst = list.length - 1;
    var d1 = list[lst].create_time;
    d1 = d1.substring(0, 19);
    d1 = d1.replace(/-/g, '/');
    var timestamp1 = new Date(d1).getTime();

    var d2 = nlist.create_time = that.getNowFormatDate();
    d2 = d2.substring(0, 19);
    d2 = d2.replace(/-/g, '/');
    var timestamp2 = new Date(d2).getTime();
    console.log(timestamp1);
    console.log(timestamp2);
    console.log((Number(timestamp2) - Number(timestamp1)));
    if ((Number(timestamp2) - Number(timestamp1)) < 3600000) {
      nlist.showTime = false;
    } else {
      nlist.showTime = true;
    }
    list.push(nlist);
    that.setData({
      newslist: list
    })
    that.setData({
      toView: 'msg-' + (that.data.newslist.length - 1)
    })
  },

  audioPlay: function (e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    var theAudio = that.data.newslist;
    var file = e.currentTarget.dataset.audio;
    for (var i = 0; i < theAudio.length; i++) {
      theAudio[i].isaudio = true;
      theAudio[i].noPlay = true;
    }
    theAudio[index].isaudio = false;
    theAudio[index].noPlay = false;

    wx.setInnerAudioOption({
      obeyMuteSwitch: false,
      success: function (e) {
        console.log(e)
        console.log('play success')
      },
      fail: function (e) {
        console.log(e)
        console.log('play fail')
      }
    })

    innerAudioContext.src = file
    innerAudioContext.obeyMuteSwitch = false
    innerAudioContext.play()
    innerAudioContext.onPlay(res => {
      console.log('recorder play start')
    })

    innerAudioContext.onEnded(res => {
      console.log('recorder onEnded start')
      theAudio[index].isaudio = true;
      theAudio[index].noPlay = true;
    })

    that.setData({
      newslist: theAudio
    })
  },

  // 结束播放录音
  audioStopPlay: function (e) {
    const that = this
    var index = e.currentTarget.dataset.index;
    var theAudio = that.data.newslist;
    var file = e.currentTarget.dataset.audio;
    theAudio[index].isaudio = true;
    theAudio[index].noPlay = true;

    innerAudioContext.src = file
    innerAudioContext.stop()
    innerAudioContext.onStop(res => {
      console.log('tap stop')
    })
    that.setData({
      newslist: theAudio
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    console.log(11);
    var that = this;


    that.data.sk.close();


    wx.onSocketClose(function () {
      console.log('Socket关闭');
     
    });
    clearInterval(that.data.setInter);

    let url2 = '/user_api/onLine';
    let params2 = {
      uid: app.globalData.userInfo.id,
      on_line_uid: 0
    }
    app.HttpPostSend(url2, params2, function (res) {

    });

  },

})